/* 折扣游戏 - 弹幕射击游戏 */
class DiscountGame {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.gameRunning = false;
        this.gamePaused = false;
        this.score = 0;
        this.killCount = 0;
        this.discount = 0;
        this.gameTime = 0;
        this.maxTime = 20; // 20秒游戏时间
        this.killTarget = 20; // 20个敌人获得最高折扣
        
        // 游戏对象
        this.player = null;
        this.enemies = [];
        this.bullets = [];
        this.enemyBullets = [];
        
        // 图片资源
        this.backgroundImage = null;
        this.breadImage = null;
        this.imagesLoaded = 0;
        this.totalImages = 2;
        
        // 游戏参数
        this.canvasWidth = 720;
        this.canvasHeight = 600;
        this.gridSize = 20;
        this.gameSpeed = 60;
        this.gameLoop = null;
        this.lastTime = 0;
        
        // 难度递增
        this.currentWave = 0;
        this.speedMultiplier = 1.0;
        this.maxSpeedMultiplier = 1.5;
        this.lastSpawnTime = 0;
        this.spawnInterval = 2000; // 2秒生成一波敌人
        
        // 玩家移动控制
        this.keys = {
            left: false,
            right: false,
            up: false,
            down: false,
            shift: false
        };
        
        this.init();
    }

    init() {
        this.bindEvents();
        this.setupCanvas();
        this.loadImages();
        this.initPlayer();
    }

    bindEvents() {
        // 游戏控制按钮
        const startGameBtn = document.getElementById('startGame');
        if (startGameBtn) {
            startGameBtn.addEventListener('click', this.startGame.bind(this));
        }
        
        const pauseGameBtn = document.getElementById('pauseGame');
        if (pauseGameBtn) {
            pauseGameBtn.addEventListener('click', this.togglePause.bind(this));
        }
        
        const resetGameBtn = document.getElementById('resetGame');
        if (resetGameBtn) {
            resetGameBtn.addEventListener('click', this.resetGame.bind(this));
        }
        
        const applyDiscountBtn = document.getElementById('applyDiscount');
        if (applyDiscountBtn) {
            applyDiscountBtn.addEventListener('click', this.applyDiscount.bind(this));
        }
        
        // 键盘控制
        document.addEventListener('keydown', this.handleKeyPress.bind(this));
        document.addEventListener('keyup', this.handleKeyRelease.bind(this));
    }

    setupCanvas() {
        this.canvas = document.getElementById('gameCanvas');
        if (!this.canvas) {
            console.error('Game canvas not found');
            return;
        }
        
        this.ctx = this.canvas.getContext('2d');
        this.canvas.width = this.canvasWidth;
        this.canvas.height = this.canvasHeight;
        
        // 设置canvas样式
        this.canvas.style.border = '2px solid #333';
        this.canvas.style.backgroundColor = '#000';
    }

    loadImages() {
        // 加载背景图片
        this.backgroundImage = new Image();
        this.backgroundImage.onload = () => {
            this.imagesLoaded++;
            console.log('背景图片加载完成');
        };
        this.backgroundImage.onerror = () => {
            console.error('背景图片加载失败');
            this.imagesLoaded++;
        };
        this.backgroundImage.src = 'game/6561761762323_.pic.jpg';

        // 加载面包图片
        this.breadImage = new Image();
        this.breadImage.onload = () => {
            this.imagesLoaded++;
            console.log('面包图片加载完成');
        };
        this.breadImage.onerror = () => {
            console.error('面包图片加载失败');
            this.imagesLoaded++;
        };
        this.breadImage.src = 'game/bread.png';
    }

    initPlayer() {
        this.player = {
            x: this.canvasWidth / 2,
            y: this.canvasHeight - 60,
            width: 30,
            height: 30,
            speed: 5,
            shootTimer: 0,
            shootInterval: 10,
            direction: 1,
            ultUsed: false,
            ultActive: false,
            ultRemaining: 0
        };
    }

    startGame() {
        if (this.gameRunning) return;
        
        this.gameRunning = true;
        this.gamePaused = false;
        this.score = 0;
        this.killCount = 0;
        this.discount = 0;
        this.gameTime = 0;
        this.currentWave = 0;
        this.speedMultiplier = 1.0;
        this.enemies = [];
        this.bullets = [];
        this.enemyBullets = [];
        this.lastSpawnTime = 0;
        
        this.initPlayer();
        this.updateUI();
        this.gameLoop = requestAnimationFrame(this.update.bind(this));
        
        // 隐藏开始按钮，显示暂停按钮
        const startBtn = document.getElementById('startGame');
        const pauseBtn = document.getElementById('pauseGame');
        if (startBtn) startBtn.style.display = 'none';
        if (pauseBtn) pauseBtn.style.display = 'inline-block';
    }

    togglePause() {
        this.gamePaused = !this.gamePaused;
        if (!this.gamePaused && this.gameRunning) {
            this.gameLoop = requestAnimationFrame(this.update.bind(this));
        }
    }

    resetGame() {
        this.gameRunning = false;
        this.gamePaused = false;
        this.score = 0;
        this.killCount = 0;
        this.discount = 0;
        this.gameTime = 0;
        this.currentWave = 0;
        this.speedMultiplier = 1.0;
        this.enemies = [];
        this.bullets = [];
        this.enemyBullets = [];
        
        this.initPlayer();
        this.updateUI();
        this.draw();
        
        // 显示开始按钮，隐藏暂停按钮
        const startBtn = document.getElementById('startGame');
        const pauseBtn = document.getElementById('pauseGame');
        if (startBtn) startBtn.style.display = 'inline-block';
        if (pauseBtn) pauseBtn.style.display = 'none';
    }

    update(currentTime) {
        if (!this.gameRunning || this.gamePaused) return;
        
        const deltaTime = currentTime - this.lastTime;
        this.lastTime = currentTime;
        
        this.gameTime += deltaTime / 1000;
        
        // 检查游戏是否结束
        if (this.gameTime >= this.maxTime) {
            this.endGame(true);
            return;
        }
        
        this.updateGame(deltaTime);
        this.draw();
        
        if (this.gameRunning) {
            this.gameLoop = requestAnimationFrame(this.update.bind(this));
        }
    }

    updateGame(deltaTime) {
        // 更新玩家
        this.updatePlayer();
        
        // 生成敌人
        this.spawnEnemies();
        
        // 更新敌人
        this.updateEnemies();
        
        // 更新子弹
        this.updateBullets();
        
        // 更新敌人子弹
        this.updateEnemyBullets();
        
        // 碰撞检测
        this.checkCollisions();
        
        // 更新UI
        this.updateUI();
    }

    updatePlayer() {
        // 玩家移动（通过键盘控制）
        const speed = this.keys.shift ? this.player.speed * 2 : this.player.speed; // Shift加速
        
        if (this.keys.left) {
            this.player.x = Math.max(0, this.player.x - speed);
            this.player.direction = -1;
        }
        if (this.keys.right) {
            this.player.x = Math.min(this.canvasWidth - this.player.width, this.player.x + speed);
            this.player.direction = 1;
        }
        if (this.keys.up) {
            this.player.y = Math.max(0, this.player.y - speed);
        }
        if (this.keys.down) {
            this.player.y = Math.min(this.canvasHeight - this.player.height, this.player.y + speed);
        }
        
        // 射击
        this.player.shootTimer++;
        if (this.player.shootTimer >= this.player.shootInterval) {
            this.shoot();
            this.player.shootTimer = 0;
        }
        
        // 大招
        if (this.player.ultActive) {
            this.player.ultRemaining -= 1/60;
            if (this.player.ultRemaining <= 0) {
                this.player.ultActive = false;
            }
        }
    }

    shoot() {
        // 创建子弹
        this.bullets.push({
            x: this.player.x - 15,
            y: this.player.y,
            width: 4,
            height: 10,
            speed: 8
        });
        this.bullets.push({
            x: this.player.x + 15,
            y: this.player.y,
            width: 4,
            height: 10,
            speed: 8
        });
    }

    spawnEnemies() {
        const currentTime = Date.now();
        if (currentTime - this.lastSpawnTime > this.spawnInterval) {
            this.currentWave++;
            this.speedMultiplier = Math.min(this.speedMultiplier * 1.03, this.maxSpeedMultiplier);
            
            // 生成2-4个敌人
            const enemyCount = Math.min(2 + Math.floor(this.currentWave / 2), 6);
            for (let i = 0; i < enemyCount; i++) {
                this.enemies.push({
                    x: Math.random() * (this.canvasWidth - 40) + 20,
                    y: -30,
                    width: 20,
                    height: 20,
                    speedX: (Math.random() - 0.5) * 2 * this.speedMultiplier,
                    speedY: 1.5 * this.speedMultiplier,
                    shootTimer: 0,
                    shootInterval: Math.max(120, 180 / this.speedMultiplier),
                    health: 3
                });
            }
            
            this.lastSpawnTime = currentTime;
        }
    }

    updateEnemies() {
        for (let i = this.enemies.length - 1; i >= 0; i--) {
            const enemy = this.enemies[i];
            
            // 移动
            enemy.x += enemy.speedX;
            enemy.y += enemy.speedY;
            
            // 边界检查
            if (enemy.x < 0 || enemy.x > this.canvasWidth - enemy.width) {
                enemy.speedX *= -1;
            }
            
            // 射击
            enemy.shootTimer++;
            if (enemy.shootTimer >= enemy.shootInterval) {
                this.enemyBullets.push({
                    x: enemy.x + enemy.width / 2,
                    y: enemy.y + enemy.height,
                    width: 6,
                    height: 10,
                    speed: 3 * this.speedMultiplier
                });
                enemy.shootTimer = 0;
            }
            
            // 移除超出屏幕的敌人
            if (enemy.y > this.canvasHeight) {
                this.enemies.splice(i, 1);
            }
        }
    }

    updateBullets() {
        for (let i = this.bullets.length - 1; i >= 0; i--) {
            const bullet = this.bullets[i];
            bullet.y -= bullet.speed;
            
            if (bullet.y < 0) {
                this.bullets.splice(i, 1);
            }
        }
    }

    updateEnemyBullets() {
        for (let i = this.enemyBullets.length - 1; i >= 0; i--) {
            const bullet = this.enemyBullets[i];
            bullet.y += bullet.speed;
            
            if (bullet.y > this.canvasHeight) {
                this.enemyBullets.splice(i, 1);
            }
        }
    }

    checkCollisions() {
        // 玩家子弹击中敌人
        for (let i = this.bullets.length - 1; i >= 0; i--) {
            const bullet = this.bullets[i];
            for (let j = this.enemies.length - 1; j >= 0; j--) {
                const enemy = this.enemies[j];
                if (this.isColliding(bullet, enemy)) {
                    enemy.health--;
                    this.bullets.splice(i, 1);
                    
                    if (enemy.health <= 0) {
                        this.killCount++;
                        this.score += 100;
                        this.enemies.splice(j, 1);
                    }
                    break;
                }
            }
        }
        
        // 敌人子弹击中玩家
        for (let i = this.enemyBullets.length - 1; i >= 0; i--) {
            const bullet = this.enemyBullets[i];
            if (this.isColliding(bullet, this.player)) {
                this.endGame(false);
                return;
            }
        }
        
        // 敌人撞击玩家
        for (let i = this.enemies.length - 1; i >= 0; i--) {
            const enemy = this.enemies[i];
            if (this.isColliding(enemy, this.player)) {
                this.endGame(false);
                return;
            }
        }
    }

    isColliding(rect1, rect2) {
        return rect1.x < rect2.x + rect2.width &&
               rect1.x + rect1.width > rect2.x &&
               rect1.y < rect2.y + rect2.height &&
               rect1.y + rect1.height > rect2.y;
    }

    endGame(success) {
        this.gameRunning = false;
        
        if (success) {
            // 计算折扣
            if (this.killCount >= 20) {
                this.discount = 15; // 85折 (15% 折扣)
            } else if (this.killCount >= 10) {
                this.discount = 10; // 90折 (10% 折扣)
            } else if (this.killCount >= 5) {
                this.discount = 5; // 95折 (5% 折扣)
            } else {
                this.discount = 0; // 无折扣
            }
        } else {
            this.discount = 0; // 死亡无折扣
        }
        
        this.showGameResult();
    }

    showGameResult() {
        const gameResult = document.getElementById('gameResult');
        const finalScore = document.getElementById('finalScore');
        const finalDiscount = document.getElementById('finalDiscount');
        
        if (gameResult && finalScore && finalDiscount) {
            finalScore.textContent = this.killCount;
            finalDiscount.textContent = this.discount + '%';
            gameResult.style.display = 'block';
        }
        
        this.updateUI();
    }

    applyDiscount() {
        // 通知父页面应用折扣
        if (window.checkoutManager) {
            window.checkoutManager.applyGameDiscount(this.discount);
        }
        
        // 关闭游戏弹窗
        const modal = document.getElementById('discountGameModal');
        if (modal) {
            modal.style.display = 'none';
        }
    }

    updateUI() {
        const gameScore = document.getElementById('gameScore');
        const discountPercent = document.getElementById('discountPercent');
        const timeLeft = document.getElementById('timeLeft');
        
        if (gameScore) {
            gameScore.textContent = this.killCount;
        }
        
        if (discountPercent) {
            let discount = 0;
            if (this.killCount >= 20) {
                discount = 15;
            } else if (this.killCount >= 10) {
                discount = 10;
            } else if (this.killCount >= 5) {
                discount = 5;
            }
            discountPercent.textContent = discount + '%';
        }
        
        if (timeLeft) {
            const remaining = Math.max(0, this.maxTime - this.gameTime);
            timeLeft.textContent = Math.ceil(remaining);
        }
    }

    handleKeyPress(e) {
        if (!this.gameRunning || this.gamePaused) return;
        
        // 处理按键按下
        switch(e.key) {
            case 'ArrowLeft':
                this.keys.left = true;
                break;
            case 'ArrowRight':
                this.keys.right = true;
                break;
            case 'ArrowUp':
                this.keys.up = true;
                break;
            case 'ArrowDown':
                this.keys.down = true;
                break;
            case 'Shift':
                this.keys.shift = true;
                break;
            case 'x':
            case 'X':
                if (!this.player.ultUsed) {
                    this.player.ultActive = true;
                    this.player.ultUsed = true;
                    this.player.ultRemaining = 5;
                    this.enemyBullets = []; // 清除所有敌人子弹
                }
                break;
        }
    }

    handleKeyRelease(e) {
        if (!this.gameRunning || this.gamePaused) return;
        
        // 处理按键释放
        switch(e.key) {
            case 'ArrowLeft':
                this.keys.left = false;
                break;
            case 'ArrowRight':
                this.keys.right = false;
                break;
            case 'ArrowUp':
                this.keys.up = false;
                break;
            case 'ArrowDown':
                this.keys.down = false;
                break;
            case 'Shift':
                this.keys.shift = false;
                break;
        }
    }

    draw() {
        if (!this.ctx) return;
        
        // 清空画布
        this.ctx.fillStyle = '#000';
        this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
        
        // 绘制背景图片
        if (this.backgroundImage && this.backgroundImage.complete) {
            this.ctx.drawImage(this.backgroundImage, 0, 0, this.canvasWidth, this.canvasHeight);
        } else {
            // 绘制背景网格（备用）
            this.drawGrid();
        }
        
        // 绘制玩家
        this.drawPlayer();
        
        // 绘制敌人
        this.drawEnemies();
        
        // 绘制子弹
        this.drawBullets();
        
        // 绘制敌人子弹
        this.drawEnemyBullets();
        
        // 绘制UI
        this.drawUI();
    }

    drawGrid() {
        this.ctx.strokeStyle = '#333';
        this.ctx.lineWidth = 1;
        
        for (let x = 0; x < this.canvasWidth; x += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.canvasHeight);
            this.ctx.stroke();
        }
        
        for (let y = 0; y < this.canvasHeight; y += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.canvasWidth, y);
            this.ctx.stroke();
        }
    }

    drawPlayer() {
        // 绘制面包图片
        if (this.breadImage && this.breadImage.complete) {
            this.ctx.drawImage(this.breadImage, this.player.x, this.player.y, this.player.width, this.player.height);
        } else {
            // 备用：绘制红色方块
            this.ctx.fillStyle = '#ff0000';
            this.ctx.fillRect(this.player.x, this.player.y, this.player.width, this.player.height);
        }
        
        // 绘制玩家方向指示
        this.ctx.fillStyle = '#ffff00';
        if (this.player.direction > 0) {
            this.ctx.fillRect(this.player.x + this.player.width - 5, this.player.y + 5, 5, 5);
        } else {
            this.ctx.fillRect(this.player.x, this.player.y + 5, 5, 5);
        }
        
        // 大招效果
        if (this.player.ultActive) {
            this.ctx.strokeStyle = '#ff00ff';
            this.ctx.lineWidth = 3;
            this.ctx.beginPath();
            this.ctx.arc(this.player.x + this.player.width/2, this.player.y + this.player.height/2, 100, 0, Math.PI * 2);
            this.ctx.stroke();
        }
    }

    drawEnemies() {
        this.ctx.fillStyle = '#0000ff';
        this.enemies.forEach(enemy => {
            this.ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
        });
    }

    drawBullets() {
        this.ctx.fillStyle = '#ffff00';
        this.bullets.forEach(bullet => {
            this.ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
        });
    }

    drawEnemyBullets() {
        this.ctx.fillStyle = '#ff0000';
        this.enemyBullets.forEach(bullet => {
            this.ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
        });
    }

    drawUI() {
        this.ctx.fillStyle = '#ffffff';
        this.ctx.font = '16px Arial';
        
        // 时间
        const remaining = Math.max(0, this.maxTime - this.gameTime);
        this.ctx.fillText(`时间: ${Math.ceil(remaining)}s`, 10, 25);
        
        // 击杀数
        this.ctx.fillText(`击杀: ${this.killCount}/${this.killTarget}`, 10, 45);
        
        // 分数
        this.ctx.fillText(`分数: ${this.score}`, 10, 65);
        
        // 当前折扣
        let discount = 0;
        if (this.killCount >= 20) {
            discount = 15;
        } else if (this.killCount >= 10) {
            discount = 10;
        } else if (this.killCount >= 5) {
            discount = 5;
        }
        this.ctx.fillText(`折扣: ${discount}%`, 10, 85);
        
        // 大招状态
        if (this.player.ultUsed) {
            this.ctx.fillText('大招: 已使用', 10, 105);
        } else {
            this.ctx.fillText('大招: 按X键使用', 10, 105);
        }
    }
}

// 初始化游戏
let discountGame = null;

document.addEventListener('DOMContentLoaded', function() {
    discountGame = new DiscountGame();
});
